package com.wisdudu.blank.ui.user;

import android.content.Intent;
import android.databinding.ObservableField;
import android.os.Bundle;

import com.kelin.mvvmlight.base.ViewModel;
import com.kelin.mvvmlight.command.ReplyCommand;
import com.orhanobut.logger.Logger;
import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.bean.PersonalInfo;
import com.wisdudu.blank.data.bean.UserInfo;
import com.wisdudu.blank.data.repo.UserRepo;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.NextErrorSubscriber;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.ProgressSubscriber;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.SubscriberOnNextListener;
import com.wisdudu.blank.support.rxbus.RxBus;
import com.wisdudu.blank.support.rxbus.RxBusFlag;
import com.wisdudu.blank.support.widget.loading.LoadingProgressDialog;
import com.wisdudu.blank.ui.common.SelectImageActivity;
import com.wisdudu.blank.ui.common.SelectYMDActivity;
import com.wisdudu.frame.support.util.ComputeUtil;

import java.text.ParseException;

/**
 * Created by ypp on 2016/8/16.
 */
public class UserInfoUpdateVM implements ViewModel {

    public final ObservableField<String> faces = new ObservableField<>();
    public final ObservableField<String> phoneNum = new ObservableField<>();
    public final ObservableField<String> nickname = new ObservableField<>();
    public final ObservableField<Integer> sex = new ObservableField<>();
    public final ObservableField<Integer> age = new ObservableField<>();

    private UserInfoUpdateFragment mFragment;
    private UserRepo userRepo;
    private String birthday;

    public UserInfoUpdateVM(UserInfoUpdateFragment fragment) {
        userRepo = Injection.provideUserRepo();
        mFragment = fragment;
        userRepo.getPersonalInfo(userRepo.getUid())
                .doOnSubscribe(() -> {
                    UserInfo userInfo = userRepo.getUserInfo();
                    faces.set(userInfo.getFaces());
                    phoneNum.set(userInfo.getUsername());
                    nickname.set(userInfo.getNickname());
                    sex.set(userInfo.getSex());
                    age.set(userInfo.getAge());
                    birthday = userInfo.getBirthday();
                })
                .compose(mFragment.bindToLifecycle())
                .subscribe(new ProgressSubscriber<>(new SubscriberOnNextListener<PersonalInfo>() {
                    @Override
                    public void onNext(PersonalInfo personalInfo, LoadingProgressDialog pd) {
                        faces.set(personalInfo.getInfo().getFaces());
                        nickname.set(personalInfo.getInfo().getNickname());
                        sex.set(Integer.valueOf(personalInfo.getInfo().getSex()));
                        age.set(Integer.valueOf(personalInfo.getInfo().getAge()));
                        birthday = personalInfo.getInfo().getBirthday();
                    }
                }, mFragment.mActivity, "正在加载..."));

    }


    public ReplyCommand onNameClick = new ReplyCommand(this::addNickFragment);


    public ReplyCommand onSexClick = new ReplyCommand(this::addSexFragment);


    public ReplyCommand onAvatarClick = new ReplyCommand(() -> {
        Logger.d("头像点击");
        entryPicSelected();
    });

    public ReplyCommand onAgeClick = new ReplyCommand(this::enrtySelectYmd);

    private void entryPicSelected() {
        Intent intent = new Intent(mFragment.getActivity(), SelectImageActivity.class);
        intent.putExtra(RxBusFlag.ENABLE_SYSTEM_IMG, true);
        intent.putExtra(RxBusFlag.MAX_SELECTED_IMG, 1);
        mFragment.startActivityForResult(intent, UserInfoUpdateFragment.REQUEST_SELECT_IMAGE);
    }

    private void addSexFragment() {
        UserSexCheckFragment fragment = new UserSexCheckFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(UserSexCheckFragment.EXTRA_SEX, sex.get());
        fragment.setArguments(bundle);
        mFragment.addFragment(fragment);
        RxBus.getDefault().toObserverable(Integer.class).compose(mFragment.bindToLifecycle())
                .subscribe(new NextErrorSubscriber<Integer>() {
                    @Override
                    public void onNext(Integer sex) {
                        Logger.d("修改性别成功，%s", nickname);
                        UserInfoUpdateVM.this.sex.set(sex);
                    }
                });
    }

    private void addNickFragment() {
        UserNickEditFragment fragment = new UserNickEditFragment();
        Bundle bundle = new Bundle();
        bundle.putString(UserNickEditFragment.EXTRA_NICKNAME, nickname.get());
        fragment.setArguments(bundle);
        mFragment.addFragment(fragment);
        RxBus.getDefault().toObserverable(String.class).compose(mFragment.bindToLifecycle()).subscribe(new NextErrorSubscriber<String>() {
            @Override
            public void onNext(String nickname) {
                Logger.d("修改昵称成功，%s", nickname);
                UserInfoUpdateVM.this.nickname.set(nickname);
            }
        });
    }

    private void enrtySelectYmd() {
        Intent intent = new Intent(mFragment.getActivity(), SelectYMDActivity.class);
        intent.putExtra(RxBusFlag.SELECT_YMD, birthday);
        intent.putExtra(RxBusFlag.SELECT_YMD_FLAG, 2);
        mFragment.startActivityForResult(intent, UserInfoUpdateFragment.REQUEST_SELECT_BIRTHDAY);
    }


    public void setBirthday(String birthday) {
        this.birthday = birthday;
        Logger.d("修改生日成功，%s", birthday);
        try {
            age.set(ComputeUtil.getAgeByBirthday(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public void editAvatar(String avatar) {
        userRepo.editAvatar(avatar).subscribe(new ProgressSubscriber<String>(new SubscriberOnNextListener<String>() {
            @Override
            public void onNext(String s, LoadingProgressDialog pd) {
                faces.set(s);
                Logger.d("修改头像成功");
            }
        }, mFragment.mActivity, "正在修改...", 1000));
    }
}
